package com.gxsf.wechatbook.controller;

import com.gxsf.wechatbook.pojo.Admin;
import com.gxsf.wechatbook.pojo.College;
import com.gxsf.wechatbook.pojo.Notice;
import com.gxsf.wechatbook.repo.AdminRepository;
import com.gxsf.wechatbook.repo.CollegeRepository;
import com.gxsf.wechatbook.repo.NoticeRepository;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.io.FileInputStream;
import java.util.List;
import java.util.Optional;

/**
 * @author BeijiRonin
 * @version 1.0.0
 * @date 2021/1/19 9:55
 */
@RestController
@RequestMapping("/messy_json")
@CrossOrigin
@Slf4j
@Api(tags = "messy_json 不重要的接口")
public class MessyController {
    @Autowired
    NoticeRepository noticeRepository;
    @Autowired
    AdminRepository adminRepository;
    @Autowired
    CollegeRepository collegeRepository;

    @ApiOperation("公告")
    @PostMapping("/notice.json")
    public NoticeResult notice() {
        NoticeResult noticeResult = new NoticeResult();
        Notice notice = noticeRepository.findFirst1ByOrderByNoticeIdDesc();
        noticeResult.setNotice(notice);
        Optional<Admin> byId = adminRepository.findById(notice.getAdminId());
        if (byId.isPresent()) {
            Admin admin = byId.get();
            noticeResult.setAdmin(admin);
        }
        return noticeResult;
    }

    @ApiOperation("返回本地图片，使用：http://localhost:4567/messy_json/img?path=???")
    @GetMapping(value = "/img", produces = MediaType.IMAGE_JPEG_VALUE)
    @ResponseBody
    public byte[] test(@RequestParam String path) throws Exception {
        if (path.equals("undefined")) {
            return null;
        }
        File file = new File(path);
        FileInputStream inputStream = new FileInputStream(file);
        byte[] bytes = new byte[inputStream.available()];
        inputStream.read(bytes, 0, inputStream.available());
        return bytes;
    }

    @PostMapping("/colleges.json")
    @ApiOperation("返回所有专业")
    public List<College> colleges() {
        return collegeRepository.findAll();
    }

    @Data
    public static class NoticeResult {
        Notice notice;
        Admin admin;
    }
}
